// INIT VARIABLES - SMARTY
var CURRENCY_SYMBOL = '￥';

if (jQuery.validator) {
    jQuery.validator.setDefaults({
        errorClass: 'has-error',
        validClass: 'has-success',
        ignore: "",
        highlight: function(element, errorClass, validClass) {
            $(element).closest('.form-group').removeClass('has-success').addClass('has-error');
            $('.error-textbox').html('请检查错误字段，修改后再提交').show();
        },
        unhighlight: function(element, errorClass, validClass) {
            $(element).closest('.form-group').removeClass('has-error').addClass('has-success');
        },
        errorPlacement: function(error, element) {

        },
        submitHandler: function(form) {
            $('.error-textbox').hide();
            var formID = $(form).attr('id');
            var formCheck = $(form).attr('data-attr-id');
            if (formCheck == undefined || formCheck == "") {
                formCheck = $(form).attr('id');
            }
            switch (formCheck) {
                case 'product-form':
                    addCart(formID);
                    break;
                case 'login-form':
                case 'register-form':
                    $('#signup-btn').addClass('disabled').attr('disabled', 'disabled');
                    userLogin(formID);
                    break;

                case 'checkout2-form':
                    checkout2(formID);
                    break;

                case 'checkout3-form':
                    $('#payment-btn').html('处理中...').attr('disabled', 'disabled');
                    /*var paymentOption = 'Credit Card';
                     >>> NOW USING MEASUREMENT PROTOCOL
                    ga('ec:setAction', 'checkout_option', {
                        'step': 2,
                        'option': paymentOption
                    });
                    ga('oldTracker.ec:setAction', 'checkout_option', {
                        'step': 2,
                        'option': paymentOption
                    });
                    ga('oldTracker.send', 'event', 'Checkout', 'Payment', paymentOption);
                    ga('send', 'event', 'Checkout', 'Payment', paymentOption);
                    */
                    form.submit();
                    break;

                case 'reset-pass-form':
                    resetPass(formID);
                    break;

                case 'student-form':
                    AssignStudentClass(formID);
                    break;

                case 'update-student-form':
                    UpdateStudentDetails(formID);
                    break;

                default:
                    form.submit();
            }
        }
    });
}


$('.modifier').change(function() {
    calculatePrice();
});

$('.gt-zero').change(function() {
    if (parseInt($(this).val()) < 1 || $(this).val() == '') {
        $(this).val('1');
    }
});

$('.unsigned-int').keyup(function() {
    if (this.value != this.value.replace(/[^0-9]/g, '')) {
        this.value = this.value.replace(/[^0-9]/g, '');
    }
});

$('.shopping-cart-menu').hover(function() {
    if ($('.nav-itemNumber').html() > 0)
        $('#shopping-cart-pop:hidden').fadeIn(200);
}, function() {
    $('#shopping-cart-pop:visible').fadeOut(200);
});

var running = false;

function calculatePrice() {
    //NOT WORKING WITH SELECT-PLUGIN ==> PRODUCT PRICE SHOULDN'T CHANGE 
    var price = parseFloat($('#cal-price').attr('value'));
    $('select .modifier').each(function() {
        price = price + parseFloat($('option:selected', this).attr('price'));
    });
    $('#cal-price').html(CURRENCY_SYMBOL + price.formatMoney(2, '.', ','));
    $('#price').val(price.toFixed(2));
}


function userLogin(form) {
    if (running) {
        return false; }
    running = true;
    $('body').css('cursor', 'wait');
    var datastring = $('#' + form).serialize();
    $.ajax({
        type: "POST",
        url: "/process/user",
        cache: false,
        data: datastring,
        dataType: "html",
        success: function(data) {
            try {
                var obj = $.parseJSON(data);
                if (obj.error) {
                    $('#' + form).find('.error-alert').find('strong').html(obj.error);
                    $('#' + form).find('.error-alert').fadeIn('slow');
                } else {
                    window.location.href = obj.url;
                }

            } catch (err) {
                console.log('TRY-CATCH error');
            }
            $('#signup-btn').removeClass('disabled').removeAttr('disabled');
            $('body').css('cursor', 'default');
            running = false;
        },
        error: function() {
            $('body').css('cursor', 'default');
            $('#signup-btn').removeClass('disabled').removeAttr('disabled');
            running = false;
            console.log('AJAX error');
        }
    });
}

function resetPass(form) {
    $('body').css('cursor', 'wait');
    var datastring = $('#' + form).serialize();
    $.ajax({
        type: "POST",
        url: "/process/user",
        cache: false,
        data: datastring,
        dataType: "html",
        success: function(data) {
            try {
                var obj = $.parseJSON(data);
                if (obj.error) {
                    $('#' + form).find('.success-alert').hide();
                    $('#' + form).find('.error-alert').find('strong').html(obj.error);
                    $('#' + form).find('.error-alert').fadeIn('slow');
                } else {
                    $('#' + form).find('.error-alert').hide();
                    $('#' + form).find('.success-alert').find('strong').html(obj.success);
                    $('#' + form).find('.success-alert').fadeIn('slow');
                    $('#' + form).find('.form-group').hide();
                    $('#reset-pass-title').hide();
                }

            } catch (err) {
                console.log('TRY-CATCH error');
            }
            $('body').css('cursor', 'default');
        },
        error: function() {
            $('body').css('cursor', 'default');
            console.log('AJAX error');
        }
    });
}

function addCart(form) {
    $('body').css('cursor', 'wait');
    $('.btn-primary').addClass('disabled');
    var datastring = $('#' + form).serialize();
    $.ajax({
        type: "POST",
        url: "/process/cart",
        cache: false,
        data: datastring,
        dataType: "html",
        success: function(data) {
            try {
                var obj = $.parseJSON(data);
                if (obj.url && $(window).width() < 760) {
                    window.location.href = obj.url;
                }
                if (obj.itemsCount > 0) {
                    $('.nav-itemNumber').html(obj.itemsCount).show();
                } else {
                    $('.nav-itemNumber').html(obj.itemsCount).hide();
                }
                $('.nav-subtotal').html(CURRENCY_SYMBOL + obj.subtotal);
                $('#shopping-cart-pop').html(obj.popoverShopCart);
                $("html, body").animate({ scrollTop: $('#shopping-cart-pop').scrollTop() }, '1000', 'swing');
                $('#shopping-cart-pop')
                $('#shopping-cart-pop').fadeIn(200);
                $('#cart-notification').fadeIn().find('strong').html(obj.message);
                setTimeout(function() {
                    $('#shopping-cart-pop').fadeOut(200);
                }, 4000);

                // ga('ec:addProduct', {
                //     'id': obj.product.id,
                //     'name': obj.product.name,
                //     'category': obj.product.category,
                //     'brand': obj.product.brand,
                //     'variant': obj.product.variant,
                //     'price': obj.product.price,
                //     'quantity': obj.product.quantity
                // });
                // ga('ec:setAction', 'add');
                var fullname = obj.product.name;
                if (obj.product.variant) {
                    fullname += ' | ' + obj.product.variant
                }
                // ga('send', 'event', 'Add to Cart', 'click', fullname);
                // ga('oldTracker.ec:addProduct', {
                //     'id': obj.product.id,
                //     'name': obj.product.name,
                //     'category': obj.product.category,
                //     'brand': obj.product.brand,
                //     'variant': obj.product.variant,
                //     'price': obj.product.price,
                //     'quantity': obj.product.quantity
                // });
                // ga('oldTracker.ec:setAction', 'add');
                var fullname = obj.product.name;
                if (obj.product.variant) {
                    fullname += ' | ' + obj.product.variant
                }
                // ga('oldTracker.send', 'event', 'Add to Cart', 'click', fullname);

            } catch (err) {
                console.log('TRY-CATCH error');
            }
            $('body').css('cursor', 'default');
            $('.btn-primary').removeClass('disabled');
        },
        error: function() {
            $('body').css('cursor', 'default');
            console.log('AJAX error');
            $('.btn-primary').removeClass('disabled');
        }
    });
}

function updateCart() {
    $('body').css('cursor', 'wait');
    var datastring = $("#shopping-cart-form").serialize();
    $.ajax({
        type: "POST",
        url: "/process/cart",
        cache: false,
        data: 'action=updateCart&' + datastring,
        dataType: "html",
        success: function(data) {
            try {
                var obj = $.parseJSON(data);
                var priceunits = obj.priceunits;
                var pricemodifier = obj.pricemodifier;
                var subtotals = obj.subtotals;
                var totals = obj.totals;
                $('#shopping-cart-pop').html(obj.popoverShopCart);
                if (obj.itemsCount > 0) {
                    $('.nav-itemNumber').html(obj.itemsCount).show();
                } else {
                    $('.nav-itemNumber').html(obj.itemsCount).hide();
                }
                /*$('.nav-subtotal').html(CURRENCY_SYMBOL+obj.totals['subtotal']);*/
                if (subtotals) {
                    /*$.each(pricemodifier, function(id, value){
                        if(value === "0%"){
                            $('#qty-discount-'+id).html('');
                        }else{
                            $('#qty-discount-'+id).html('(-'+value+')');
                        }
                    });*/
                    $.each(priceunits, function(id, value) {
                        amount = parseFloat(value);
                        $('#priceunit-' + id).html(CURRENCY_SYMBOL + amount.formatMoney(2, '.', ','));
                    });
                    $.each(subtotals, function(id, value) {
                        amount = parseFloat(value);
                        $('#subtotal-' + id).html(CURRENCY_SYMBOL + amount.formatMoney(2, '.', ','));
                    });
                    $.each(totals, function(id, value) {
                        amount = parseFloat(value);
                        if (id == 'total') {
                            $('#subtotal').attr('data-value', amount);
                            $('#subtotal').html(CURRENCY_SYMBOL + amount.formatMoney(2, '.', ','));
                        } else if (id == 'discount') {
                            $('#' + id).html(CURRENCY_SYMBOL + amount.formatMoney(2, '.', ','));
                        }
                    });
                    //renderShippingMethods(obj.shippingMethods);
                    calculateTotal();
                } else {
                    alert('Error: Quantity exceeded available spots.');
                }
            } catch (err) {
                console.log('TRY-CATCH error - ' + err);
            }
            $('body').css('cursor', 'default');
        },
        error: function() {
            $('body').css('cursor', 'default');
            console.log('AJAX error');
        }
    });
}

function deleteItem(ID) {
    $('body').css('cursor', 'wait');
    $('#' + ID).fadeTo("fast", 0.5);
    var frmTkn = $("#formToken").val();
    $.ajax({
        type: "POST",
        url: "/process/cart",
        cache: false,
        data: 'action=DeleteItem&cartitem_id=' + ID + '&formToken=' + frmTkn,
        dataType: "html",
        success: function(data) {
            try {
                var obj = $.parseJSON(data);
                var response = obj.response;
                var totals = obj.totals;
                if (obj.itemsCount > 0) {
                    $('.nav-itemNumber').html(obj.itemsCount).show();
                } else {
                    $('.nav-itemNumber').html(obj.itemsCount).hide();
                }
                $('.nav-subtotal').html(CURRENCY_SYMBOL + obj.totals['subtotal']);
                $('#shopping-cart-pop').html(obj.popoverShopCart);
                if (response) {
                    // ga('ec:addProduct', {
                    //     'id': obj.product.id,
                    //     'name': obj.product.name,
                    //     'category': obj.product.category,
                    //     'brand': obj.product.brand,
                    //     'variant': obj.product.variant,
                    //     'price': obj.product.price,
                    //     'quantity': obj.product.quantity
                    // });
                    // ga('ec:setAction', 'remove');

                    var fullname = obj.product.name;
                    if (obj.product.variant) {
                        fullname += ' | ' + obj.product.variant
                    }
                    // ga('send', 'event', 'Remove from Cart', 'click', fullname);
                    // ga('oldTracker.ec:addProduct', {
                    //     'id': obj.product.id,
                    //     'name': obj.product.name,
                    //     'category': obj.product.category,
                    //     'brand': obj.product.brand,
                    //     'variant': obj.product.variant,
                    //     'price': obj.product.price,
                    //     'quantity': obj.product.quantity
                    // });
                    // ga('oldTracker.ec:setAction', 'remove');

                    var fullname = obj.product.name;
                    if (obj.product.variant) {
                        fullname += ' | ' + obj.product.variant
                    }
                    // ga('oldTracker.send', 'event', 'Remove from Cart', 'click', fullname);

                    if (parseInt(obj.itemsCount) > 0) {
                        $('#' + ID).hide('slow');
                        $.each(totals, function(id, value) {
                            amount = parseFloat(value);
                            $('#' + id).html(CURRENCY_SYMBOL + amount.formatMoney(2, '.', ','));
                        });
                    } else {
                        location.reload();
                    }
                } else {
                    $('#' + ID).fadeTo("fast", 1);
                    alert('Item cannot be deleted');
                }
            } catch (err) {
                $('#' + ID).fadeTo("slow", 1);
                console.log('TRY-CATCH error');
            }
            $('body').css('cursor', 'default');
        },
        error: function() {
            $('#' + ID).fadeTo("slow", 1);
            console.log('AJAX error');
            $('body').css('cursor', 'default');
        }
    });
}


function checkout2(form) {
    $('body').css('cursor', 'wait');
    if (running) {
        return false; }
    running = true;
    var datastring = $("#" + form).serialize();
    $.ajax({
        type: "POST",
        url: "/process/cart",
        cache: false,
        data: datastring,
        dataType: "html",
        success: function(data) {
            try {
                var obj = $.parseJSON(data);
                if (obj.response) {
                    if (obj.countClassOnCart > 0) {
                        goCheckoutStudent();
                    } else {
                        goCheckout3();
                    }
                    $('#billing-summary').html(obj.billing);
                    $('#shipping-summary').html(obj.shipping);

                    var shippingOption = 'Standard';
                    // ga('ec:setAction', 'checkout_option', {
                    //     'step': 1,
                    //     'option': shippingOption
                    // });
                    // ga('send', 'event', 'Checkout', 'Shipping', shippingOption);
                    // ga('ec:setAction', 'checkout', {
                    //     'step': 2
                    // });
                    // ga('send', 'pageview');
                    // ga('oldTracker.ec:setAction', 'checkout_option', {
                    //     'step': 1,
                    //     'option': shippingOption
                    // });
                    // ga('oldTracker.send', 'event', 'Checkout', 'Shipping', shippingOption);
                    // ga('oldTracker.ec:setAction', 'checkout', {
                    //     'step': 2
                    // });
                    // ga('oldTracker.send', 'pageview');
                }
            } catch (err) {
                console.log('TRY-CATCH error');
            }
            running = false;
            $('body').css('cursor', 'default');
        },
        error: function() {
            running = false;
            $('body').css('cursor', 'default');
            console.log('AJAX error');
        }
    });

}

//function calculateTotal(str) {
//    var value = parseFloat(str);
//    $('#shipping-fee-value').html(CURRENCY_SYMBOL+ value.toFixed(2));
//    var total = parseFloat($('#total').attr('amount')) + value ;
//    $('.total-amount').html(CURRENCY_SYMBOL+ total.toFixed(2));
//    var gst = (parseFloat($('#gst').attr('amount')) + value ) /10 ;
//    $('#gst').html(CURRENCY_SYMBOL+ gst.toFixed(2));
//}

function addProductCart(ID, QTY, PRICE) {
    $('body').css('cursor', 'wait');
    $.ajax({
        type: "POST",
        url: "/process/cart",
        cache: false,
        data: "action=ADDTOCART&product_id=" + ID + "&quantity=" + QTY + "&price=" + PRICE,
        dataType: "html",
        success: function(data) {
            try {
                var obj = $.parseJSON(data);
                if (obj.url) {
                    window.location.href = obj.url;
                }

            } catch (err) {
                console.log('TRY-CATCH error');
            }
            $('body').css('cursor', 'default');
        },
        error: function() {
            $('body').css('cursor', 'default');
            console.log('AJAX error');
        }
    });
}

$('.quantity').change(function() {
    updateCart();
});

function renderShippingMethods(OPT) {
    if ($('#shippingMethod').get(0).tagName == "select") {
        $('#shippingMethod').empty();
        $.each(OPT, function(id, value) {
            $('#shippingMethod').append($('<option>', {
                value: value,
                text: id
            }));
        });
    }
}

$('#shippingMethod').change(function() {
    var price = parseFloat($(this).val());
    $('#shipping-fee').html(CURRENCY_SYMBOL + price.formatMoney(2, '.', ','));
    calculateTotal();
});

function updateShipping() {
    $('body').css('cursor', 'wait');
    var postcode = $("#postcodesh").val();
    if ($("#chksame:checked").length == 1 || postcode == undefined) {
        postcode = $("#postcode-field").val();
    }
    var datastring = postcode;
    $.ajax({
        type: "POST",
        url: "/process/cart",
        cache: false,
        data: 'action=updatePostage&postcode=' + datastring,
        dataType: "html",
        success: function(data) {
            try {
                var obj = $.parseJSON(data);
                var postagefee = obj.postagefee;
                if (isArray(postagefee)) {
                    // Iterate the array and do stuff
                    //                    if (postagefee.length == 1) {
                    var amount = parseFloat(postagefee[0].postage_price);
                    $('#shippingMethod').val(amount);
                    $('#shipMethod').val(postagefee[0].postage_name);
                    $('#postageID').val(postagefee[0].postage_id);
                    calculateTotal();
                    //                    } else {
                    //alert('Error: Cannot be updated');
                    //                    }
                } else {
                    if (postagefee) {
                        var amount = parseFloat(postagefee.postage_price);
                        $('#shippingMethod').val(amount);
                        $('#shipMethod').val(postagefee.postage_name);
                        $('#postageID').val(postagefee.postage_id);
                        calculateTotal();
                    } else {
                        alert('Error: Cannot be updated');
                    }
                }
            } catch (err) {
                console.log('TRY-CATCH error - ' + err);
            }
            $('body').css('cursor', 'default');
        },
        error: function() {
            $('body').css('cursor', 'default');
            console.log('AJAX error');
        }
    });
}

function calculateTotal() {
    var subtotal = parseFloat($('#subtotal').attr('data-value'));
    var fee = $('#shippingMethod').val();
    if (fee) {
        fee = parseFloat(fee);
        $('#shipping-fee').html(CURRENCY_SYMBOL + fee.formatMoney(2, '.', ','));
    } else {
        fee = parseFloat(0);
        $('#shipping-fee').html('$0.00');
    }
    var total = subtotal + fee;
    $('#total').html(CURRENCY_SYMBOL + total.formatMoney(2, '.', ','));
    $('#shipMethod').val($('#shippingMethod option:selected').text());
};

function scrolltodiv(id) {
    $('html,body').animate({
        scrollTop: $(id).offset().top
    });
}

function isArray(what) {
    return Object.prototype.toString.call(what) === '[object Array]';
}
Number.prototype.formatMoney = function(c, d, t) {
    var n = this,
        c = isNaN(c = Math.abs(c)) ? 2 : c,
        d = d == undefined ? "." : d,
        t = t == undefined ? "," : t,
        s = n < 0 ? "-" : "",
        i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "",
        j = (j = i.length) > 3 ? j % 3 : 0;
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};

function convert_to_mysql_date_format(str) {
    var dateArr = str.split("/");
    return dateArr[2] + '-' + dateArr[1] + '-' + dateArr[0];
}

function setDateValue(id, date) {
    $("#" + id).val(convert_to_mysql_date_format(date));
}

function AddStudent(formID) {
    $('body').css('cursor', 'wait');
    $('#' + formID).find('.btn').addClass('disabled');
    var cnt = $("#cnt").val();
    $.ajax({
        type: "POST",
        url: "/process/cart",
        cache: false,
        data: 'action=studentTemplate&cnt=' + cnt,
        dataType: "html",
        success: function(data, textStatus) {
            try {
                var obj = $.parseJSON(data);
                if (obj.success) {
                    $('#student-wrapper').append(obj.template);
                    $(".existing-student").hide();
                    $('.saveFake').hide();
                    $('.stuformbuttons').hide();
                    $('#student-form').validate();
                    cnt++;
                    $("#cnt").val(cnt);
                    $('select').selectBoxIt();
                    $('#dob' + cnt).val($('#dobyear' + cnt).val() + '-' + $('#dobmonth' + cnt).val() + '-' + $('#dobday' + cnt).val());
                }
            } catch (err) {}
            $('body').css('cursor', 'default');
            $('#' + formID).find('.btn').removeClass('disabled');
        },
        error: function() {
            $('body').css('cursor', 'default');
            $('#' + formID).find('.btn').removeClass('disabled');
            console.log('AJAX error');
        }
    });

}

function EditStudent(studentID) {
    $('#' + studentID).find(".fake-student").hide();
    $('.stuformbuttons').hide();
    $('.existing-student').hide();
    $('.saveFake').hide();
    $('#' + studentID).find(".addstuform").show();
    $('#' + studentID).find('input[type="checkbox"]').each(function() {
        $(this).addClass('classterm-chk').parent().removeClass('text-disabled');
    });
    $('#' + studentID).find('.small.text-danger').each(function() {
        $(this).remove();
    });
}


function SaveStudent(studentID) {
    var fname = $('#' + studentID).find(".new_name").val();
    //var lname = $('#' + studentID).find(".new_surname").val();
    var fullname = fname.trim();
    $('#' + studentID).attr('data-fullname', fullname.toLowerCase());
    $('#' + studentID).find(".fake-student").find('b').html(fullname);
    $('#' + studentID).find(".addstuform").hide();
    $('#' + studentID).find(".fake-student").show().addClass('saveFake');
    $('.existing-student').show();
    $('.saveFake').show();
    $('.stuformbuttons').show();
    if ($('.students').length > 0) {
        /*CheckSelectedClasses();*/
        ValidateClassesByAge();
        ValidateStudentForTrials(studentID);
        $('#step3-btn').show();
    } else {
        $('#step3-btn').hide();
    }

}

function CancelAddStudent(studentID) {
    $('#' + studentID).remove();
    $('.existing-student').show();
    $('.saveFake').show();
    $('.stuformbuttons').show();
    if ($('.students').length > 0) {
        /*CheckSelectedClasses();*/
        $('#step3-btn').show();
    } else {
        $('#step3-btn').hide();
    }
}

function AssignStudentClass(form) {
    $('body').css('cursor', 'wait');
    var datastring = $("#" + form).serialize();
    $.ajax({
        type: "POST",
        url: "/process/cart",
        cache: false,
        data: datastring,
        dataType: "html",
        success: function(data) {
            try {
                var obj = $.parseJSON(data);
                if (obj.error) {
                    $('#' + form).find('.error-alert').find('strong').html(obj.error);
                    $('#' + form).find('.error-alert').fadeIn('slow');
                } else if (obj.success) {
                    location.reload();
                    /*$('#'+form).find('.error-alert').hide(); 
                     
                    $('#student-summary-wrapper').show();
                    if (obj.classtermStudentArr){
                        $('#student-summary').html('');
                        $.each(obj.classtermStudentArr, function(id, value){
                            $('#student-summary').append( value+'<br>');
                        });
                    }else{
                        $('#student-summary').html('None');
                    }
                    goCheckout3();
                    $.each(obj.remove, function(id, value){
                        $('#student'+value).html('');
                    });
                    $.each(obj.totals, function(id, value){
                        amount = parseFloat(value);
                        if(id == 'total'){
                            $('#to').attr('data-value', amount);
                            $('#total').html(CURRENCY_SYMBOL+amount.formatMoney(2, '.', ','));
                        }else if(id == 'discount'){
                            $('#'+id).html('-$'+amount.formatMoney(2, '.', ','));
                        }else{
                            $('#'+id).html(CURRENCY_SYMBOL+amount.formatMoney(2, '.', ','));
                        }
                    });*/
                }
            } catch (err) {
                console.log('TRY-CATCH error:' + err);
            }
            $('body').css('cursor', 'default');
        },
        error: function() {
            $('body').css('cursor', 'default');
            console.log('AJAX error');
        }
    });

}

function UpdateStudentDetails(form) {
    $('body').css('cursor', 'wait');
    var datastring = $("#" + form).serialize();
    $.ajax({
        type: "POST",
        url: "/process/user",
        cache: false,
        data: datastring,
        dataType: "html",
        success: function(data) {
            try {
                var obj = $.parseJSON(data);
                if (obj.error) {
                    $('#' + form).find('.success-alert').hide();
                    $('#' + form).find('.error-alert').find('strong').html(obj.error);
                    $('#' + form).find('.error-alert').fadeIn('slow');
                } else if (obj.success) {
                    $('#' + form).find('.error-alert').hide();
                    $('#' + form).find('.success-alert').find('strong').html(obj.success);
                    $('#' + form).find('.success-alert').fadeIn('slow');
                }
            } catch (err) {
                console.log('TRY-CATCH error:' + err);
            }
            $('body').css('cursor', 'default');
        },
        error: function() {
            $('body').css('cursor', 'default');
            console.log('AJAX error');
        }
    });

}

function CheckSelectedClasses(OBJ) {
    if (OBJ) {
        var CARTITEM = $(OBJ).attr('data-cartitem');
        var QTY = $(OBJ).attr('data-quantity');
        if ($('.classterm-chk[data-cartitem="' + CARTITEM + '"]:checked').length >= QTY) {
            $('.classterm-chk[data-cartitem="' + CARTITEM + '"]:checkbox:not(":checked")').attr('disabled', 'disabled').parent().addClass('text-disabled');

        } else {
            $('.classterm-chk[data-cartitem="' + CARTITEM + '"]:checkbox:not(":checked")').removeAttr('disabled').parent().removeClass('text-disabled');
        }
    } else {
        var doneArr = new Array()
        $('.classterm-chk').each(function() {
            var CARTITEM = $(this).attr('data-cartitem');
            if ($.inArray(CARTITEM, doneArr) == -1) {
                doneArr.push(CARTITEM);
                var QTY = $(this).attr('data-quantity');
                if ($('.classterm-chk[data-cartitem="' + CARTITEM + '"]:checked').length >= QTY) {
                    $('.classterm-chk[data-cartitem="' + CARTITEM + '"]:checkbox:not(":checked")').attr('disabled', 'disabled').parent().addClass('text-disabled');

                } else {
                    $('.classterm-chk[data-cartitem="' + CARTITEM + '"]:checkbox:not(":checked")').removeAttr('disabled').parent().removeClass('text-disabled');
                }
            }
        });
    }
}

function ValidateStudentForTrials(ID) {
    var newfullname = $('#' + ID).attr('data-fullname');
    var student_exist = false;
    $('.students').each(function() {
        var fullname = $(this).attr('data-fullname');
        if ((newfullname == fullname) && ($(this).attr('id') != ID)) {
            student_exist = true;
            return false;
        }
    });
    if (student_exist) {
        $('#' + ID).find('.classterm-chk.T').each(function() {
            $(this).removeClass('classterm').removeAttr('checked').parent().addClass('text-disabled').append(' <div class="small text-danger">This child is not eligible for a trial class</div>');
        });
    }

}

function ValidateClassesByAge() {
    var CNT = $("#cnt").val();
    for (i = 1; i <= CNT; i++) {
        var DOB = $('#dob' + i).val();
        var d1 = new Date(DOB);
        var d2 = new Date();
        var AGE = DateDiff.inMonths(d1, d2);
        $('.classterm-chk[data-cnt="' + i + '"]').each(function() {
            var MINAGE = $(this).attr('data-min-age');
            var MAXAGE = $(this).attr('data-max-age');
            console.log('cnt:' + i + ' => age=' + AGE);
            if (AGE < MINAGE || AGE > MAXAGE) {
                $(this).removeClass('classterm-chk').parent().attr('class','text-danger').append(' <div class="small text-danger">该课程可能不适合您孩子的年龄。如果要继续，请选择该课程并点击下一步或<a href="/contact us">联系我们</a>寻求帮助</div>');
            } else {
                $(this).parent().attr('class','text-success');
            }
        });
    }
}

function EnrolFromMembersArea(STUDENT_ID, TERM_ID, CLASS_ID, URL) {
    $.ajax({
        type: "POST",
        url: "/process/cart",
        cache: false,
        data: 'action=PreSelectClasstermStudent&student_id=' + STUDENT_ID + '&term_object_id=' + TERM_ID + '&class_object_id=' + CLASS_ID,
        dataType: "html",
        success: function(data, textStatus) {
            try {
                var obj = $.parseJSON(data);
                window.location.assign(URL);
                if (obj.success) {}

            } catch (err) {}
            $('body').css('cursor', 'default');
        },
        error: function() {
            $('body').css('cursor', 'default');
            console.log('AJAX error');
        }
    });

}
var DateDiff = {

    inDays: function(d1, d2) {
        var t2 = d2.getTime();
        var t1 = d1.getTime();

        return parseInt((t2 - t1) / (24 * 3600 * 1000));
    },

    inWeeks: function(d1, d2) {
        var t2 = d2.getTime();
        var t1 = d1.getTime();

        return parseInt((t2 - t1) / (24 * 3600 * 1000 * 7));
    },

    inMonths: function(d1, d2) {
        var d1Y = d1.getFullYear();
        var d2Y = d2.getFullYear();
        var d1M = d1.getMonth();
        var d2M = d2.getMonth();

        return (d2M + 12 * d2Y) - (d1M + 12 * d1Y);
    },

    inYears: function(d1, d2) {
        return d2.getFullYear() - d1.getFullYear();
    }
}
